#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    int find(int x, vector<int>& p) {
        if (p[x] != x)p[x] = find(p[x], p);
        return p[x];
    }

    int citys(vector<vector<int> >& m) {
        int n = m.size();
        vector<int> p(n + 1);
        for (int i = 1; i <= n; i++)p[i] = i;

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (m[i][j] == 1) {
                    int x = find(i + 1, p);
                    int y = find(j + 1, p);
                    if (x == y)continue;
                    p[x] = y;
                }
            }
        }
        int ans = n;
        for (int i = 1; i <= n; i++) {
            if (p[i] != i)ans--;
        }
        return ans;
    }
};